package cn.tangsihai.user.service.impl;

import cn.tangsihai.basic.exception.MyException;
import cn.tangsihai.basic.util.SendMsg;
import cn.tangsihai.basic.util.StrUtils;
import cn.tangsihai.user.constant.UserConstant;
import cn.tangsihai.user.domain.User;
import cn.tangsihai.user.mapper.UserMapper;
import cn.tangsihai.user.service.IUserService;
import cn.tangsihai.user.service.IVerifycodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.security.Key;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class VerifycodeServiceImpl implements IVerifycodeService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void smsCode(Map<String, String> param) {
        String phone = param.get("phone");
        String type = param.get("type");
        // 1.手机号不为空
        if (phone.isEmpty()){
            throw new MyException("手机号不能为空！");
        }

        // 判断是注册还是微信登录绑定
        if (type.equals("register")){ // 注册
            // 2.判断手机号是否存在与user表中
            User user = userMapper.findByPhone(phone);
            if (user != null){
                throw new MyException("手机号已注册，请登录！");
            }
            String registerKey = UserConstant.REGISTER_PREFIX + phone;
            sendCode(registerKey);
        } else { // 微信登录绑定
            String banderKey = UserConstant.BANDER_PREFIX + phone;
            sendCode(banderKey);
        }

    }

    /**
     * 发送验证码
     * @param redisKey
     */
    public void sendCode(String redisKey){
        // 3.三分钟过期：从redis中取：有，没过期
        // key：业务标识register_prefix + 手机号
        Object tmpCode = redisTemplate.opsForValue().get(redisKey);
        String code = null;
        if (tmpCode != null){ // 没过期
            // 3.1 判断验证码是否超过一分钟，没超过：抛出异常
            // vlue："时间戳" + ":" + code
            String time = tmpCode.toString().split(":")[0];
            long currentTime = System.currentTimeMillis();
            if (currentTime - Long.valueOf(time) <= 1 * 60 * 1000){
                // 没超过
                throw new MyException("已发送验证码，请勿重复操作!");
            } else {
                // 3.2 超过：刷新之前验证码的过期时间
                code = tmpCode.toString().split(":")[1];
            }
        } else { // 取不到，过期
            // 4.无：过期，重新生成验证码
            code = StrUtils.getComplexRandomString(6);
        }
        // key：业务标识register_prefix + 手机号
        Object key = redisKey;
        // vlue："时间戳" + ":" + code
        Object vlue = System.currentTimeMillis() + ":" + code;
        // 向redis中存入验证码，设置三分钟过期
        redisTemplate.opsForValue().set(key, vlue, 3L, TimeUnit.MINUTES);
        // 发送验证码
////        SendMsg.sendSMS(phone, "验证码：" + code + ",有效时间为三分钟，请在三分钟内完成注册。");
        System.out.println(code);
    }
}
